package model

import (
	"gorm.io/gorm/clause"
	"server/common"
	"server/pkg/app"
)

type TestCaseLabel struct {
	Model
	Label string `gorm:"column:label;not null;type:varchar(16);unique" json:"name"`
	Desc  string `gorm:"column:desc;not null;type:varchar(255);unique" json:"desc"`
}

func (label *TestCaseLabel) TableName() string {
	return "case_label"
}

func (label *TestCaseLabel) List(page *app.Page) ([]TestCaseLabel, int64) {
	labels := []TestCaseLabel{}
	var count int64
	if err := common.DB.Debug().Order("id desc").Limit(page.Size).Offset((page.Page - 1) * page.Size).Find(&labels).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return labels, count
	}
	return labels, count
}

func (label *TestCaseLabel) Info() TestCaseLabel {
	var labels TestCaseLabel
	if err := common.DB.Where("name = ?", label.Label).Find(&labels).Error; err != nil {
		return labels
	}
	return labels
}

func (label *TestCaseLabel) SearchByName(page *app.Page, key string) ([]TestCaseLabel, int64, error) {
	labels := []TestCaseLabel{}
	var count int64
	if err := common.DB.Where("name like ?", "%"+key+"%").Order("starttime desc").Limit(page.Size).Offset((page.Page - 1) * page.Size).Find(&labels).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return labels, count, err
	}
	return labels, count, nil
}

func (label *TestCaseLabel) Create() error {
	if err := common.DB.Model(&TestCaseLabel{}).Omit(clause.Associations).Create(&label).Error; err != nil {
		return err
	}
	return nil
}

func (label *TestCaseLabel) Update() error {
	if err := common.DB.Where("name = ?", label.Label).Updates(&label).Error; err != nil {
		return err
	}
	return nil
}

func (label *TestCaseLabel) Delete() error {
	if err := common.DB.Where("name = ?", label.Label).Delete(&label).Error; err != nil {
		return err
	}
	return nil
}
